package com.example.wastewater.service.impl;

import cn.hutool.core.date.DateTime;
import com.example.wastewater.common.convention.exception.ServiceException;
import com.example.wastewater.dto.req.LogAddReqDTO;
import com.example.wastewater.service.IOperationLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class OperationLogServiceImpl implements IOperationLogService {
    private final ObjectMapper objectMapper;
    private final StringRedisTemplate stringRedisTemplate;
    private final static String LOG_KEY = "wastewater:logs";
    @Override
    public void logAdd(LogAddReqDTO requestParam) {
        Map<String, Object> logEntry = new HashMap<>();
        logEntry.put("recorderName", requestParam.getRecorderName());
        logEntry.put("action", requestParam.getAction());
        logEntry.put("timestamp", new DateTime(System.currentTimeMillis()));
        logEntry.put("description", requestParam.getDescription());

        try {
            String logEntryJson = objectMapper.writeValueAsString(logEntry);
            stringRedisTemplate.opsForList().leftPush(LOG_KEY, logEntryJson);
        } catch (JsonProcessingException e) {
            throw new ServiceException("处理日志出错");
        }
    }

    @Override
    public List<String> getLogs() {
        return stringRedisTemplate.opsForList().range(LOG_KEY, 0, -1);
    }
}
